package com.sfh.tourist.base;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sfh.tourist.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ImageSelectProgressView extends RecyclerView implements BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener {
    private final static String EMPTY = "-1";
    // 适配器
    private FileAdapter mRefreshAdapter;

    private boolean delete = true;

    private int mMaxSize = 5;

    private int mRowSize = 4;

    private OnItemSelectListener listener;

    public ImageSelectProgressView(@NonNull Context context) {
        super(context);
        init(null);
    }

    public ImageSelectProgressView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public ImageSelectProgressView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        this.mRefreshAdapter = new FileAdapter();
        this.setAdapter(mRefreshAdapter);
        this.mRefreshAdapter.setOnItemClickListener(this);
        this.mRefreshAdapter.setOnItemChildClickListener(this);
        ((SimpleItemAnimator) this.getItemAnimator()).setSupportsChangeAnimations(false);

        int size = dp2px(14);
        this.addItemDecoration(CommItemDecoration.createHorizontal(getContext(), size));
        this.setLayoutManager(new GridLayoutManager(getContext(), mRowSize));
        this.addEmpty();
    }

    /**
     * 单位转换: dp -> px
     */
    int dp2px(float dp) {
        return (int) (getContext().getResources().getDisplayMetrics().density * dp + 0.5);
    }

    /***
     *设置显示
     * @param maxSize 最大数据
     * @param rowSize 每行数量
     */
    public void setShowSize(int maxSize, int rowSize) {

        this.mMaxSize = maxSize;
        this.mRowSize = rowSize;
        this.setLayoutManager(new GridLayoutManager(getContext(), rowSize));
    }

    /***
     *设置监听
     */
    public void setOnItemSelectListener(OnItemSelectListener listener) {

        this.listener = listener;

    }

    /***
     * 设置是否可以删除 默认可删除
     * @param delete
     */
    public void setDelete(boolean delete) {

        this.delete = delete;
    }

    /***
     * 获取上传成功数据集合
     * @return
     */
    public List<ProcessFile> getDataList() {

        // 去除 + 数据
        List<ProcessFile> data = new ArrayList<>(5);
        for (ProcessFile image : mRefreshAdapter.getData()) {
            if (!TextUtils.isEmpty(image.getImagUrl()) && !TextUtils.equals(EMPTY, image.getImagUrl())) {
                data.add(image);
            }
        }
        return data;
    }

    /***
     * 获取上传成功数据集合
     * @return
     */
    public String getDataStr() {

        // 去除 + 数据
        StringBuffer url = new StringBuffer();
        for (ProcessFile image : mRefreshAdapter.getData()) {
            if (!TextUtils.isEmpty(image.getImagUrl()) && !TextUtils.equals(EMPTY, image.getImagUrl())) {
                url.append(image.getImagUrl()).append(",");
            }
        }
        return url.substring(0, url.length() - 1).toString();
    }

    /***
     * 全部数据（包含空白选择项）
     * @return
     */
    public List<ProcessFile> getAllData() {
        return mRefreshAdapter.getData();
    }

    public FileAdapter getRefreshAdapter() {
        return mRefreshAdapter;
    }

    /***
     * 上传图片
     * @param file
     */
    public void onUpLoadStart(List<String> file) {

        if (file == null || file.isEmpty()) {
            return;
        }

        List<ProcessFile> temp = new ArrayList<>(file.size());
        for (String path : file) {
            ProcessFile image = new ProcessFile();
            image.setLoading();
            image.setTag(path);
            temp.add(image);
        }

        List<ProcessFile> images = this.mRefreshAdapter.getData();
        // 移除最后空的图片
        images.remove(images.size() - 1);
        images.addAll(temp);
        this.mRefreshAdapter.notifyItemRangeChanged(0, images.size());
        this.addEmpty();
    }

    /***
     * 上传成功
     * @param old
     * @param url
     */
    public void onUpLoadFileSuccess(String old, String url) {

        List<ProcessFile> images = mRefreshAdapter.getData();

        for (int i = 0; i < images.size(); i++) {
            ProcessFile image = images.get(i);
            if (TextUtils.isEmpty(image.getImagUrl()) && TextUtils.equals(image.getTag(), old)) {
                image.setSuccess();
                image.setImagUrl(url);
                mRefreshAdapter.notifyItemChanged(i);
                return;
            }
        }
    }

    /***
     * 上传失败
     * @param old
     */
    public void onUpLoadFileError(String old) {

        List<ProcessFile> images = mRefreshAdapter.getData();

        for (int i = 0; i < images.size(); i++) {
            ProcessFile image = images.get(i);
            if (TextUtils.isEmpty(image.getImagUrl()) && TextUtils.equals(image.getTag(), old)) {
                image.setFail();
                mRefreshAdapter.notifyItemChanged(i);
                return;
            }
        }
    }


    /***
     * 删除图片
     * @param position
     */
    public void deleteImage(int position) {

        this.mRefreshAdapter.remove(position);
        this.addEmpty();
    }

    /***
     * 初始化
     * @param data
     */
    public void setNewData(List<ProcessFile> data) {

        if (data == null) {
            data = new ArrayList<>(mMaxSize);
        }
        // 最后添加一个空
        if (data.size() < mMaxSize) {
            ProcessFile emptyBean = new ProcessFile();
            emptyBean.setImagUrl(EMPTY);
            data.add(emptyBean);
        }
        this.mRefreshAdapter.setNewData(data);
    }

    /***
     * 添加空白数据
     */
    private void addEmpty() {

        final int size = this.mRefreshAdapter.getItemCount();
        if (size == 0) {
            ProcessFile emptyBean1 = new ProcessFile();
            emptyBean1.setImagUrl(EMPTY);
            this.mRefreshAdapter.addData(emptyBean1);
            return;
        }

        final int lastIndex = size - 1;
        ProcessFile lastData = this.mRefreshAdapter.getItem(lastIndex);
        // 最后一个是空数据
        if (TextUtils.equals(EMPTY, lastData.getImagUrl())) {
            return;
        }

        if (size < mMaxSize) {
            ProcessFile emptyBean1 = new ProcessFile();
            emptyBean1.setImagUrl(EMPTY);
            this.mRefreshAdapter.addData(emptyBean1);
        }

    }


    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {

        super.onMeasure(widthSpec, heightSpec);
        int width = getMeasuredWidth() / mRowSize - dp2px(14);
        this.mRefreshAdapter.setWidth(width);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        if (listener == null) {
            return;
        }
        ProcessFile data = mRefreshAdapter.getItem(position);
        if (view.getId() == R.id.ivFail) {
            data.setLoading();
            mRefreshAdapter.notifyItemChanged(position);
            listener.onUpImageClick(data.getTag());
        } else {
            listener.onDelateClick(position);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (listener == null) {
            return;
        }
        ProcessFile mData = mRefreshAdapter.getItem(position);
        if (TextUtils.equals(EMPTY, mData.getImagUrl())) {
            //这里是选择图片
            listener.onSelectImageClick(mMaxSize - position);
        } else {
            //这里是查看图片或者修改图片
            listener.onLookImageClick(this.getDataList(), position);
        }
    }


    /***
     * 点击回调
     */
    public interface OnItemSelectListener {

        /**
         * 选择上传图片
         */
        void onSelectImageClick(int surplus);

        /**
         * 重新上传图片
         */
        void onUpImageClick(String file);

        /**
         * 查看图片
         */
        void onLookImageClick(List<ProcessFile> file, int position);

        /***
         * 删除图片
         * @param position
         */
        void onDelateClick(int position);
    }

    class FileAdapter extends BaseQuickAdapter<ProcessFile, BaseViewHolder> {

        FrameLayout.LayoutParams mParams;


        public FileAdapter() {

            super(R.layout.ui_file_image_adapter);
        }

        public void setWidth(int width) {

            this.mParams = new FrameLayout.LayoutParams(width, width);
            this.notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, ProcessFile item) {

            ImageView iv = helper.getView(R.id.ivImage);
            ImageView ivFail = helper.getView(R.id.ivFail);
            if (this.mParams != null) {
                iv.setLayoutParams(mParams);
                ivFail.setLayoutParams(mParams);
            }
            helper.addOnClickListener(R.id.ivDel).addOnClickListener(R.id.ivFail);
            helper.setGone(R.id.progress, false);
            helper.setGone(R.id.ivFail, false);
            helper.setGone(R.id.ivDel, false);

            if (TextUtils.equals(EMPTY, item.getImagUrl())) {
                // 添加图片
                iv.setImageResource(R.mipmap.base_selector_view_photo_2);
            } else {
                if (delete) {
                    helper.setGone(R.id.ivDel, true);
                } else {
                    helper.setGone(R.id.ivDel, false);
                }

                if (TextUtils.isEmpty(item.getImagUrl())) {

                    if (item.getFail()) {
                        helper.setGone(R.id.ivFail, true);
                    } else if (item.getLoading()) {
                        helper.setGone(R.id.progress, true);
                    }

                    if (TextUtils.isEmpty(item.getTag())) {
                        //本地文件地址 也为空
                        helper.setGone(R.id.ivFail, true);
                        helper.setGone(R.id.progress, false);
                        iv.setImageResource(R.mipmap.base_img_error_defualt);
                    } else {
                        // 加载本地
                        this.loadFileImage(item.getTag(), iv);
                    }

                } else {
                    // 已经上传成功
                    this.loadFileImage(item.getTag(), iv);
                }
            }
        }

        private void loadFileImage(String file, ImageView iv) {
            // 加载本地
            new ImageLoaderEngine(new File(file)).error(R.mipmap.base_img_error_defualt).placeholder(R.mipmap.base_img_placeholder_defualt).into(iv);
        }
    }
}
